package cuiyt.datastructure.stack;

import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;

import java.util.HashMap;
import java.util.Stack;

/**
 * @author cyt
 * @create 2020-11-22 18:45
 */
public class Test {
    public static void main(String[] args) {
        CyStack<Character> stack = new CyStack<>();
        String test = "()";
        System.out.println(new Test().isValid1(test));
        System.out.println(new Test().isValid2(test));
    }

    static HashMap<Character, Character> map = new HashMap<>();

    static {
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');
    }

    public boolean isValid2(String str) {
        int len = str.length();
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (map.containsKey(ch)) {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                if (ch != map.get(stack.pop())) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public boolean isValid1(String str) {
        Stack<Character> stack = new Stack<>();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char ch = str.charAt(i);
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                Character left = stack.pop();
                if (left == '(' && ch != ')') {
                    return false;
                }
                if (left == '{' && ch != '}') {
                    return false;
                }
                if (left == '[' && ch != ']') {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
